let https = require('https')
let url = require('url')
let cheerio = require('cheerio')

const server = http.createServer()
server.on('request',(req,res)=>{
    res.writeHead(200,{
        'content-type':'application/json;charset=utf-8',
        'access-control-allow-origin':'*'
    })
    if(urlObj.pathname === '/api/getInfo'){
        httpget(data =>res.end(spider(data)))
    }else{
        res.end('404')
    }

})


function httpget(cb) {
    let data = ''
    https.get('https://i.maoyan.com/#movie',(res)=>{
        res.on("data",(chunk)=>{
            data += chunk
        })
        res.on('end',()=>{
            cb(data)
        })
    })
}


function spider(data){
    const $ = cheerio.load(data);
    let $movieList = $('.column.content')
    let movies = []
    $movieList.each((index,value)=>{
        movies.push({
            title:$(value).find('.title').text(),
            grade:$(value).find('.grade').text(),
            actor:$(value).find('.actor').text(),
        })
    })
    console.log(movies) 
    return JSON.stringify(movies)
}


server.listen(300,()=>{
    console.log('port 300 is listening')
})





